<template>
  <div>
    <el-card>
      <PlusSearch
          :rules="rules"
          v-model="searchParam"
          :columns="tableConfig"
          :show-number="2"
          :need-validate="true"
          @change="handleChange"
          @search="handleSearch"
          @reset="handleReset"
          :defaultValues="defaultValues"
      />
    </el-card>
    <div><br/></div>

    <el-card>
      <PlusTable ref="plusPageRef" :columns="tableConfig" :table-data="tableData"
                 :rowKey="'transaction_id'"
                 :is-selection="false" @select="handleSelect"
                 @formChange="handleFormChange"
                 :pagination="{
        total,
        modelValue: pageInfo,
        pageSizeList: [10, 20, 50],
        align: 'right'
      }"
                 @paginationChange="handlePaginationChange">
        <template v-slot:title>
          <el-button type="primary" @click="showUpload = true">导入</el-button>
          <el-button type="primary" :disabled="changedTableData.length == 0" @click="handleChange">更新</el-button>

          <el-dialog v-model="showUpload" title="选择 " width="400">
            <el-upload
                ref="uploadRef"
                class="upload-demo"
                v-model:file-list="fileList"
                drag
                :action="uploadUrl"
                :on-error="handleError"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
                :multiple=false
                accept=".xlsx"
                :auto-upload="true"
                :limit="1"
                :headers="uploadHeaders"
            >
              <el-icon class="el-icon--upload">
                <UploadFilled/>
              </el-icon>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <template #tip>
                <div class="el-upload__tip">只能上传xlsx文件</div>
              </template>
            </el-upload>
          </el-dialog>
        </template>
      </PlusTable>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {
  type PageInfo,
  type PlusColumn,
  PlusSearch,
  type PlusSearchInstance,
  PlusTable,
  useTable
} from 'plus-pro-components'
/**
 * @plus-pro-components/utils 是辅助plus-pro-components的工具包，如果需要使用，需要单独安装
 * 参考文档 https://plus-pro-components.com/api/utils/
 */
import {
  ElButton,
  ElUpload, type FormRules,
  type UploadFile,
  type UploadFiles,
  type UploadInstance,
  type UploadUserFile
} from 'element-plus'
import {UploadFilled} from "@element-plus/icons-vue";
import {computed, onMounted, reactive, type Ref, ref} from 'vue';
import {ElMessage} from 'element-plus';
import type {TransferRecord} from "../model/transfer_record.ts";
import {getWXTransferRecords} from "../api/transaction.ts";

import {useAuthStore} from "../stores/auth.ts";
import {get, remove} from 'lodash-es'
import {type FormChangeCallBackParams} from "plus-pro-components/es/components/table/src/type";

const rules = reactive<FormRules<TransferRecord>>({
  transaction_time: [{
    required: true,
    message: '请选择交易日期',
    trigger: 'change',
  }]
})

onMounted(() => {
  // searchRef.value.plusFormInstance.formInstance.rules = rules
})
const changedTableData = ref<TransferRecord[]>([]);
const totalTableData = ref<TransferRecord[]>([]);
const {tableData, total, pageInfo} = useTable<TransferRecord[]>()
const defaultValues = {
  income_or_expense: '支出',
  archived: false,
}
const searchParam: TransferRecord = ref({...defaultValues})
const handleChange = () => {
  console.log(changedTableData.value)
}
const handleFormChange = (form: FormChangeCallBackParams) => {
  const index = form.index
  const origin = tableData.value[index]
  remove(changedTableData.value, (item) => {
    return item.transaction_id === origin.transaction_id;
  });
  const newValue = form.value;
  if (newValue === get(origin, form.prop)) {
    return;
  }
  changedTableData.value.push(form.row)
}
const selections: Ref<String[]> = ref([])
const handleSearch = async (values: any) => {
  let query = values.target
  let wxTransferRecords = await getWXTransferRecords(query);
  console.log(wxTransferRecords)
  totalTableData.value = wxTransferRecords
  total.value = wxTransferRecords.length
  let _pageInfo = pageInfo.value
  console.log(_pageInfo)
  let page = _pageInfo.page
  let pageSize = _pageInfo.pageSize
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  tableData.value = wxTransferRecords.slice(startIndex, endIndex);
}

const handleSelect = (selection: any[], row: any) => {
  selections.value = selection.map((item) => item.transaction_id)
  console.log(selections.value)
}

const handleReset = () => {
  console.log('handleReset')
}

const handlePaginationChange = (_pageInfo: PageInfo): void => {
  pageInfo.value = _pageInfo
  let page = _pageInfo.page
  let pageSize = _pageInfo.pageSize
  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  tableData.value = totalTableData.value.slice(startIndex, endIndex);
}

const uploadRef = ref<UploadInstance>({} as UploadInstance);
const showUpload = ref(false);

const uploadUrl = ref('/api/wx/transaction-upload'); // 替换为你的本地接口地址
const fileList = ref<UploadUserFile[]>([])

const beforeUpload = (file: File) => {
  const isXlsx = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.name.endsWith('.xlsx');
  if (!isXlsx) {
    ElMessage.error('只能上传xlsx文件');
    return false;
  }
  return true;
};
const handleSuccess = (response: any, file: UploadFile, files: UploadFiles) => {
  console.log(file, files);
  if (response && response.data) {
    ElMessage.success('文件上传成功');
    // 调用本地接口处理文件内容
    handleFileContent(response.data);
    showUpload.value = false;
    uploadRef.value.clearFiles()
  } else {
    ElMessage.error('文件上传失败');
  }
};

const handleError = (err: any, file: UploadFile, files: UploadFiles) => {
  console.log(file, files);
  ElMessage.error(`文件上传失败: ${err.message}`);
};

const handleFileContent = (data: any) => {
  // 处理返回的文件内容
  console.log('文件内容:', data);
  // 你可以在这里将文件内容存储到 Vuex 或其他状态管理工具中
  // 或者直接在页面上展示文件内容
};
let authStore = useAuthStore();
const uploadHeaders = computed(() => ({
  // 如果 Token 存在，添加 Authorization 头；不存在则不添加（避免无效请求头）
  ...(authStore.token ? {Authorization: `Bearer ${authStore.token}`} : {})
}));
const tableConfig: PlusColumn[] = [
  {
    label: '交易时间',
    // tooltip: '名称最多显示6个字符',
    width: 160,
    prop: 'transaction_time',

    tableColumnProps: {
      showOverflowTooltip: true
    },
    valueType: 'date-picker',
    hideInForm: true
  },
  {
    label: '收/支',
    width: 70,
    prop: 'income_or_expense',
    valueType: 'select',
    options: [
      {
        label: '支出',
        value: '支出',
        color: 'red'
      },
      {
        label: '收入',
        value: '收入',
        color: 'green'
      },
      {
        label: '/',
        value: '/',
        color: 'blue'
      }
    ]
  },
  {
    label: '已归档',
    width: 70,
    prop: 'archived',
    valueType: 'switch',
    editable: true,
    fieldProps: {
      onChange: (item) => {

      }
    }
  },
  {
    label: '交易类型',
    width: 120,
    prop: 'transaction_type'
  },
  {
    label: '交易对方',
    width: 120,
    prop: 'transaction_counterparty'
  },
  {
    label: '商品',
    width: 200,
    prop: 'product'
  },

  {
    label: '金额(元)',
    width: 100,
    prop: 'amount'
  },
  {
    label: '支付方式',
    width: 200,
    prop: 'payment_method'
  },
  {
    label: '当前状态',
    width: 200,
    prop: 'current_status'
  },
  {
    label: '交易单号',
    width: 300,
    prop: 'transaction_id'
  },
  {
    label: '商户单号',
    prop: 'merchant_id',
    width: 300
  },
  {
    label: '备注',
    prop: 'notes'
  }
]
</script>
<style>
/* 可选：自定义样式 */
.upload-demo {
  width: 300px;
  margin: 50px auto;
}
</style>
